import { ChatGPTAPI } from "chatgpt";
import http from "http";
import { defer } from "utils-lib-js";
const apiKey = "openAI的apiKey";
const initChatGPT = (
  opts = {
    apiKey,
    markdown: false,
  }
) => {
  return new ChatGPTAPI(opts);
};
const chatGPTApi = initChatGPT();
const createServer = () => {
  http
    .createServer((req, res) => {
      res.setHeader("Access-Control-Allow-Origin", "*"); //设置响应头解决跨域
      if (req.url !== "/sendMsg") return sendRes(res, "not find", 404);
      let _data = "";
      req.on("data", (d) => {
        _data += d;
      });
      req.on("end", () => {
        const data = JSON.parse(_data);
        console.log(data);
        sendChatGPTMsg(data)
          .then((r) => {
            sendRes(res, JSON.stringify({ msg: r }));
          })
          .catch((err) => {
            sendRes(res, JSON.stringify(err));
          });
      });
    })
    .listen(4096, () => {
      console.log("服务开启！");
    });
};
/**
 * @name:
 * @description: 服务端响应消息
 * @param {ServerResponse} res ServerResponse实例
 * @param {*} msg 发送的消息
 * @param {*} code 状态码
 * @return {*}
 */
const sendRes = (res, msg = "", code = 200) => {
  res.writeHead(code, {
    "Content-Type": "text/plain",
    "Access-Control-Allow-Origin": "*",
  });
  res.write(msg);
  res.end();
};
/**
 * @name:
 * @description: 封装了一下ChatGPT
 * @param {*} msg 发送的消息
 * @param {*} opts 配置文件，传parentMessageId，conversationId可以关联上下文
 * @return {Promise}
 */
const sendChatGPTMsg = async ({ msg, opts }) => {
  const { promise, resolve, reject } = defer();
  chatGPTApi.sendMessage(msg, opts).catch(reject).then(resolve);
  return promise;
};

createServer();
